IF OBJECT_ID('ssf.dpnd_get_dependency_object_tree') IS NOT NULL
	DROP FUNCTION ssf.dpnd_get_dependency_object_tree
GO

CREATE FUNCTION ssf.dpnd_get_dependency_object_tree (
	@dpnd_object_name NVARCHAR(256)
)
RETURNS @dependency_object_tree TABLE (
	tree_level TINYINT NOT NULL
	, dpnd_object_id INT NOT NULL
	, header_object_id INT NOT NULL
	, dependency_type VARCHAR(128) NOT NULL
	, dpnd_object_name NVARCHAR(512) NOT NULL
	, object_type NVARCHAR(128) NOT NULL
	, change_type NVARCHAR(128)
)
AS
BEGIN
	-- ============
	/*<code_comment><![CDATA[declare local variables]]></code_comment>*/
	DECLARE	@row_count INT
				, @tree_level TINYINT = 0
	-- ============

	INSERT @dependency_object_tree
	SELECT @tree_level
		, *
	FROM ssf.dpnd_get_dependency_object(@dpnd_object_name)

	SET @row_count = @@ROWCOUNT

	WHILE @row_count > 0
	BEGIN
		SET @tree_level += 1

		INSERT @dependency_object_tree
		SELECT @tree_level
			, c.*
		FROM (
			SELECT DISTINCT dpnd_object_name
			FROM @dependency_object_tree
			WHERE tree_level = @tree_level - 1
			AND ssf.dpnd_get_header_object_id(
				CASE WHEN ISNULL(PARSENAME(dpnd_object_name, 3), PARSENAME(dpnd_object_name, 2)) IS NULL
					THEN OBJECT_SCHEMA_NAME(OBJECT_ID(dpnd_object_name)) + '.' + dpnd_object_name
					ELSE dpnd_object_name
					END
			) NOT IN (
				SELECT DISTINCT header_object_id
				FROM @dependency_object_tree
			)
		) p
		CROSS APPLY ssf.dpnd_get_dependency_object(
			CASE WHEN ISNULL(PARSENAME(p.dpnd_object_name, 3), PARSENAME(p.dpnd_object_name, 2)) IS NULL
				THEN OBJECT_SCHEMA_NAME(OBJECT_ID(p.dpnd_object_name)) + '.' + p.dpnd_object_name
				ELSE p.dpnd_object_name
				END
		) c

		SET @row_count = @@ROWCOUNT
	END

	RETURN
END
GO
